package util;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("unchecked")
public class ConvertUtil {
	
	public static <K, V> Map<K, V> toMap(List<?> list, String keyFieldName, String valueFieldName) {
		Map result = new HashMap();
		
		if (list == null || list.isEmpty()) return result;
		
		Object item = list.get(0);
		Class<?> clazz = item.getClass();
		Field keyField = null, valueField = null;
		
		while (clazz != null) {
			Field[] fields = clazz.getDeclaredFields();
			for (Field f : fields) {
				if (keyField == null) {
					if (f.getName().equals(keyFieldName)) {
						keyField = f;
						keyField.setAccessible(true);
					}
				}
				
				if (valueField == null) {
					if (f.getName().equals(valueFieldName)) {
						valueField = f;
						valueField.setAccessible(true);
					}
				}
			}
			
			if (keyField != null && valueField != null) break;
			
			clazz = clazz.getSuperclass();
		}
		
		if (keyField == null || valueField == null) return result; 
		
		try {
			for (Object o : list) {
				result.put(keyField.get(o), valueField.get(o));
			}
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
		
		return result;
	}
}
